package com.example.quartz.utils;

import com.example.quartz.component.MyScheduleJob;
import com.example.quartz.constant.QuartzConstants;
import com.example.quartz.module.sms.QuartzTask;
import org.quartz.*;

/**
 * @author: wlp
 * @description: 描述：定时任务工具类
 * @projectName: ScheduleUtils
 * @date: 2019/10/12
 * @version: V1.0.0
 */
public class SchedulerUtils {

    /**
     * 获取触发器key
     */
    public static TriggerKey getTriggerKey(Long quartzId) {
        return TriggerKey.triggerKey(QuartzConstants.TRIGGER_NAME + quartzId);
    }

    /**
     * 获取jobKey
     */
    public static JobKey getJobKey(Long quartzId) {
        return JobKey.jobKey(QuartzConstants.QUARTZ_NAME + quartzId);
    }

    /**
     * 获取表达式触发器
     */
    public static CronTrigger getCronTrigger(Scheduler scheduler, Long quartzId) {
        try {
            return (CronTrigger) scheduler.getTrigger(getTriggerKey(quartzId));
        } catch (SchedulerException e) {
            throw new RuntimeException("获取定时任务CronTrigger出现异常", e);
        }
    }

    /**
     * 创建定时任务
     */
    public static void createScheduleJob(Scheduler scheduler, QuartzTask quartzTask) {
        try {
            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(MyScheduleJob.class).withIdentity(getJobKey(quartzTask.getId())).build();
            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzTask.getQuartzCron())
                    .withMisfireHandlingInstructionDoNothing();

            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(quartzTask.getId())).withSchedule(scheduleBuilder).build();
            //放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put(QuartzConstants.QUARTZ_PARAM_KEY, quartzTask);
            scheduler.scheduleJob(jobDetail, trigger);
            //暂停任务
            if (quartzTask.getQuartzStatus() == QuartzConstants.QUARTZ_STATUS_PUSH) {
                pauseJob(scheduler, quartzTask.getId());
            }
        } catch (SchedulerException e) {
            throw new RuntimeException("创建定时任务失败", e);
        }
    }

    /**
     * 更新定时任务
     */
    public static void updateScheduleJob(Scheduler scheduler, QuartzTask quartzTask) {
        try {
            TriggerKey triggerKey = getTriggerKey(quartzTask.getId());
            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzTask.getQuartzCron())
                    .withMisfireHandlingInstructionDoNothing();
            CronTrigger trigger = getCronTrigger(scheduler, quartzTask.getId());
            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            //参数
            trigger.getJobDataMap().put(QuartzConstants.QUARTZ_PARAM_KEY, quartzTask);
            scheduler.rescheduleJob(triggerKey, trigger);
            //暂停任务
            if (quartzTask.getQuartzStatus() == QuartzConstants.QUARTZ_STATUS_PUSH) {
                pauseJob(scheduler, quartzTask.getId());
            }
        } catch (SchedulerException e) {
            throw new RuntimeException("更新定时任务失败", e);
        }
    }

    /**
     * 立即执行任务
     */
    public static void run(Scheduler scheduler, QuartzTask quartzTask) {
        try {
            //参数
            JobDataMap dataMap = new JobDataMap();
            dataMap.put(QuartzConstants.QUARTZ_PARAM_KEY, quartzTask);
            scheduler.triggerJob(getJobKey(quartzTask.getId()), dataMap);
        } catch (SchedulerException e) {
            throw new RuntimeException("立即执行定时任务失败", e);
        }
    }

    /**
     * 暂停任务
     */
    public static void pauseJob(Scheduler scheduler, Long quartzId) {
        try {
            scheduler.pauseJob(getJobKey(quartzId));
        } catch (SchedulerException e) {
            throw new RuntimeException("暂停定时任务失败", e);
        }
    }

    /**
     * 恢复任务
     */
    public static void resumeJob(Scheduler scheduler, Long quartzId) {
        try {
            scheduler.resumeJob(getJobKey(quartzId));
        } catch (SchedulerException e) {
            throw new RuntimeException("暂停定时任务失败", e);
        }
    }

    /**
     * 删除定时任务
     */
    public static void deleteScheduleJob(Scheduler scheduler, Long quartzId) {
        try {
            scheduler.deleteJob(getJobKey(quartzId));
        } catch (SchedulerException e) {
            throw new RuntimeException("删除定时任务失败", e);
        }
    }
}